package com.leyou.auth.task;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.mapper.ApplicationInfoMapper;
import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.utils.JwtUtils;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 这个类的作用: 定时任务类, 项目启动就执行,每隔24小时去授权中心申请一次token(自己给自己授权)
 */
@Slf4j
@Component
public class AppTokenHolder {

    //token刷新间隔时间
    private final static long LOAD_TOKEN_TIME = 86400000L;
    //获取token休眠时间
    private final static long LOAD_TOKEN_SLEEP_TIME = 10000L;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private ApplicationInfoMapper applicationInfoMapper;

    @Getter
    private String token;

    @Scheduled(fixedDelay = LOAD_TOKEN_TIME)
    public void loadTokenTask() throws InterruptedException {
        while (true){
            try {
                //构建载荷
                AppInfo appInfo = new AppInfo();
                appInfo.setId(jwtProperties.getApp().getId());  //id
                appInfo.setServiceName(jwtProperties.getApp().getName());   //名称
                appInfo.setTargetList(applicationInfoMapper.queryTargetIdList(jwtProperties.getApp().getId())); //拥有的权限
                //生成token
                this.token = JwtUtils.generateTokenExpireInMinutes(appInfo, jwtProperties.getPrivateKey(), jwtProperties.getApp().getExpire());
                log.info("【授权中心微服务】申请token成功");
                break;
            } catch (Exception e){
                log.error("【授权中心微服务】申请token失败: {}",e.getMessage());
            }
            Thread.sleep(LOAD_TOKEN_SLEEP_TIME);
        }
    }

}
